import { InvoiceExportApi } from "@/api/waybillManagement/businessWaybill";
import CommonHook from "@/hook/commonHook";
import FormHook from "@/hook/formHook";
import { message } from "ant-design-vue";
import { Ref } from "vue";
export default function OperationHook(state: {
  formState: { bizExportTemplateId: string | undefined };
  formDataRef: Ref<any>;
  emit: any;
  passData: Ref<Array<BusinessWaybill.ListRows>>;
  loading: Ref<boolean>;
}) {
  const { formState, formDataRef, emit, passData, loading } = state;
  const { resetFields } = FormHook({ formState });
  const { downloadFileByBlob } = CommonHook();

  const onFinish = () => {
    const { bizExportTemplateId } = formState;
    const params: Parameters<typeof InvoiceExportApi>[0] = {
      bizExportTemplateId: bizExportTemplateId as string,
      shipmentIdList: passData.value.map((t: any) => t.id)
    };
    loading.value = true;
    InvoiceExportApi(params)
      .then((res: any) => {
        const { waybillNum, itemNumber, channelName } = passData.value[0];
        const { status, data, headers } = res;
        const { filename } = headers;
        const name = filename.split(".");
        if (status === 200) {
          name[1] === "xlsx" && downloadFileByBlob(data, `${waybillNum}+${itemNumber}件+${channelName}.xlsx`);
          name[1] === "zip" && downloadFileByBlob(data, "发票导出.zip");
          message.success("操作成功!");
          emit("submit");
        }
      })
      .finally(() => (loading.value = false));
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  const resetHandle = () => {
    resetFields();
    formDataRef.value.clearValidate();
    emit("update:visible", false);
  };
  return {
    onFinish,
    onFinishFailed,
    resetHandle,
    resetFields
  };
}
